package com.bolt.report.engine.query;

import com.bolt.report.definition.DataSetDefinition;
import com.bolt.report.definition.DataSetType;
import com.bolt.report.definition.JdbcDataSourceDefinition;
import com.bolt.report.engine.pool.JdbcConnectionPool;
import com.bolt.report.exception.ReportException;
import net.sf.jasperreports.engine.JRParameter;

import java.util.Map;

public class QueryExecuteFactory {

    private JdbcConnectionPool connectionPool;

    public QueryExecuteFactory(JdbcConnectionPool connectionPool) {
        this.connectionPool = connectionPool;
    }

    public QueryExecute createQueryExecuter(DataSetDefinition dataSetDefinition, Map<String, Object> parameters) {
        DataSetType dataSetType = dataSetDefinition.getType();
        switch (dataSetType) {
            case SQL:
                createJdbcConnection(dataSetDefinition, parameters);
                return new JdbcQueryExecute(dataSetDefinition, parameters);
            case SPRING:
                return new SpringBeanQueryExecute(dataSetDefinition, parameters);
            case API:
                return new ApiHttpQueryExecute(dataSetDefinition,parameters);
            case JSON:
                return new JSONQueryExecute(dataSetDefinition);
            default:
                throw new ReportException("query executer factory not registered");
        }
    }

    private void createJdbcConnection(DataSetDefinition dataSetDefinition, Map<String, Object> parameters) {
        try {
            JdbcDataSourceDefinition dataSourceDefinition = dataSetDefinition.getJdbcConnectionDef();
            parameters.put(JRParameter.REPORT_CONNECTION, this.connectionPool.getPooledConnection(dataSourceDefinition));
        } catch (Exception ex) {
            throw new ReportException(ex);
        }

    }

}